package weifei.live.simulation.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weifei.live.simulation.entity.Adminer;
import weifei.live.simulation.entity.dto.AdminerDTO;
import weifei.live.simulation.service.AdminerService;
import weifei.web.Result;

import java.util.Date;

@RestController
@RequestMapping("/adminer")
public class AdminerController
{
    @Autowired
    private AdminerService adminerService;


    @PostMapping("/login")
    public Result login(
            @Valid @RequestBody Adminer adminer
    )
    {
        var username = adminer.getUsername();
        var password = adminer.getPassword();

        QueryWrapper<Adminer> qw_adminer = new QueryWrapper<>();
        qw_adminer.eq(Adminer.Column.Username.getName(), username);
        var a = adminer.selectOne(qw_adminer);
        if (a == null)
            return Result.failed("不存在的管理员");
        if (!a.getPassword().equals(password))
            return Result.failed("密码错误");

        var token = JWT.create()
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 86400000)) // 一天过期
                .withClaim("adminerID", a.getId())
                .sign(Algorithm.HMAC256(password));     //使用HMAC算法，password作为密钥加密
        return Result.success("登录成功", token);
    }


    // 下面有登录拦截
    @GetMapping("/getAdminerSelf")
    @PostMapping("/getAdminerSelf")
    public Result getAdminerSelf(HttpServletRequest request)
    {
        var token = request.getHeader("token");
        var adminer = this.adminerService.getAdminerByToken(token);
        if (adminer == null)
            return Result.failed("获取失败");
        return Result.success("获取成功", new AdminerDTO(adminer));
    }

}


